package com.tzstcl.sys.user.ctrl;

import com.github.pagehelper.PageInfo;
import com.tzstcl.base.ctrl.BaseCtrl;
import com.tzstcl.base.model.AjaxResult;
import com.tzstcl.commons.utils.StringUtils;
import com.tzstcl.framework.constants.AppConstants;
import com.tzstcl.sys.user.model.SysDept;
import com.tzstcl.sys.user.model.SysDeptPost;
import com.tzstcl.sys.user.model.SysPosition;
import com.tzstcl.sys.user.model.SysPost;
import com.tzstcl.sys.user.model.SysUser;
import com.tzstcl.sys.user.model.SysUserRole;
import com.tzstcl.sys.user.model.UserInfo;
import com.tzstcl.sys.user.service.SysDeptService;
import com.tzstcl.sys.user.service.SysPositionService;
import com.tzstcl.sys.user.service.SysUserService;
import com.tzstcl.sys.user.service.impl.SysDeptPostService;
import com.tzstcl.sys.user.service.impl.SysPostService;
import com.tzstcl.sys.user.service.impl.SysUserRoleService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.tzstcl.framework.shiro.ShiroUtils.getUser;

/**
 * 作者：guohy
 * 日期：2019年08月08日
 * 说明：用户表Controller
 */
@Controller
@RequestMapping("/admin/sysUser")
public class SysUserCtrl extends BaseCtrl {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService userRoleService;
    @Autowired
    private SysDeptPostService sysDeptPostService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysPostService sysPostService;
    @Autowired
    private SysPositionService sysPositionService;

    /**
     * list页面导航
     *
     * @return
     */
    @RequiresPermissions("sysUser:view")
    @RequestMapping("/toList")
    public String toList() {
        return "admin/sys/user/sysUserList";
    }

    /**
     * 获取查询的分页数据
     *
     * @param sysUser
     * @return
     */
    @RequestMapping("/list")
    @RequiresPermissions("sysUser:view")
    @ResponseBody
    public PageInfo<SysUser> list(SysUser sysUser) {
        sysUser.setSort(null);
        return sysUserService.selectPage(sysUser);
    }

    /**
     * form页面导航
     *
     * @return
     */
    @RequiresPermissions(value = {"sysUser:edite", "sysUser:add"}, logical = Logical.OR)
    @RequestMapping("/toForm")
    public String toForm(@RequestParam(value = "id", required = false) Long id, Model model) {
        if (null != id) {
            model.addAttribute("sysUser", sysUserService.getOne(id));
        }
        return "admin/sys/user/sysUserForm";
    }

    /**
     * form页面导航 详情
     *
     * @return
     */
    @RequiresPermissions("sysUser:view")
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, Model model) {
        if (null != id) {
            //用户基本信息
            SysUser user = sysUserService.getOne(id);
            user.setPassword(null);
            //用户角色
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getId());
            List<SysUserRole> list = userRoleService.findList(userRole);
            List<Long> ids = new ArrayList<>();
            for (SysUserRole role : list) {
                ids.add(role.getRoleId());
            }
            SysDeptPost sysDeptPost = sysDeptPostService.get(user.getId());
            Map<String, Object> userMap = new HashMap<>(4);
            userMap.put("roleIds", ids);
            if (sysDeptPost != null) {
                //岗位
                if (null != sysDeptPost.getPostId()) {
                    SysPost sysPost = sysPostService.getOne(sysDeptPost.getPostId());
                    user.setPost(sysPost);
                }
                //组织
                if (null != sysDeptPost.getDeptId()) {
                    SysDept sysDept = sysDeptService.getOne(sysDeptPost.getDeptId());
                    user.setDept(sysDept);
                }
                //职位
                if (null != sysDeptPost.getPositionId()) {
                    SysPosition sysPosition = sysPositionService.getOne(sysDeptPost.getPositionId());
                    user.setPosition(sysPosition);
                }
            }
            userMap.put("user", user);
            model.addAttribute("userMap", userMap);
        }
        return "admin/sys/user/sysUserDetail";
    }

    /**
     * 新增
     *
     * @param sysUser
     * @return
     */
    @RequestMapping("/add")
    @RequiresPermissions(value = {"sysUser:add"})
    @ResponseBody
    public AjaxResult add(Long[] ids, SysUser sysUser) {
        if (StringUtils.isEmpty(sysUser.getId() + "")) {
            SysUser su = new SysUser();
            su.setLoginName(sysUser.getLoginName());
            // 校验登陆账户唯一性
            //SysUser user = sysUserService.findByNameOrPass(su);
            SysUser user = sysUserService.findByNameIgnoreDelFlag(su);//无视删除标记
            if (user != null) {
                return AjaxResult.error("账户已存在，请更换不同账户名称！");
            }
        }
        if (null == ids || ids.length == 0) {
            return error("角色不能为空");
        }
        sysUserService.save(sysUser, ids);
        return success("新增成功");
    }

    /**
     * form页面导航 更新
     *
     * @return
     */
    @RequiresPermissions("sysUser:edite")
    @GetMapping("/edit/{id}")
    public String toUpdate(@PathVariable("id") Long id, Model model) {
        if (null != id) {
            //用户基本信息
            SysUser user = sysUserService.getOne(id);
            user.setPassword(null);
            //用户角色
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getId());
            List<SysUserRole> list = userRoleService.findList(userRole);
            List<Long> ids = new ArrayList<>();
            for (SysUserRole role : list) {
                ids.add(role.getRoleId());
            }
            SysDeptPost sysDeptPost = sysDeptPostService.get(user.getId());
            Map<String, Object> userMap = new HashMap<>(4);
            userMap.put("roleIds", ids);
            if (sysDeptPost != null) {
                //岗位
                /*SysPost post = new SysPost();
                post.setId(sysDeptPost.getPostId());
                SysPost sysPost = sysPostService.get(post);
                userMap.put("sysPost", sysPost);*/

                //组织
                SysDept sysDept = sysDeptService.getOne(sysDeptPost.getDeptId());

                user.setPositionId(sysDeptPost.getPositionId());
                user.setPostId(sysDeptPost.getPostId());
                user.setDept(sysDept);
            }
            userMap.put("user", user);
            model.addAttribute("userMap", userMap);
        }
        return "admin/sys/user/sysUserEdit";
    }


    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sysUser:delete")
    @ResponseBody
    public AjaxResult delete(String ids) {
        for (String str : ids.split(",")) {
            SysUser sysUser = sysUserService.getOne(Long.parseLong(str));
            if (sysUser != null && sysUser.getId().equals(AppConstants.SUPER_ADMIN)) {
                return AjaxResult.error("超级管理员 " + sysUser.getLoginName() + " 不可删除");
            }
        }
        return toAjax(sysUserService.deleteBatchIds(ids));
    }

    /**
     * 获取单条信息
     *
     * @param id
     * @return
     */
    @RequestMapping("/get")
    @RequiresPermissions("sysUser:view")
    @ResponseBody
    public AjaxResult get(Long id) {
        return success("获取信息成功", sysUserService.getOne(id));
    }

    /**
     * 校验唯一性
     * 权限配置为：多权限任选一，有新增和修改其一权限就可以访问
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/checkUnique")
    @RequiresPermissions(value = {"sysUser:add", "sysUser:edite"}, logical = Logical.OR)
    @ResponseBody
    public Map<String, Boolean> checkUnique(SysUser sysUser) {
        Map<String, Boolean> result = new HashMap<>(4);
        result.put("valid", true);
        Long id = sysUser.getId();
        sysUser.setId(null);
        List<SysUser> sysUserList = sysUserService.selectList(sysUser);
        if (StringUtils.isNotEmpty(sysUserList)) {
            if (sysUserList.size() > 0) {
                result.put("valid", false);
            } else {
                if (id != null) {
                    // 新增
                    result.put("valid", false);
                } else {
                    // 修改
                    if (!id.equals(sysUserList.get(0).getId())) {
                        result.put("valid", false);
                    }
                }
            }
        }
        return result;
    }

    /**
     * @param ids
     * @param sysUser
     * @return com.seasoft.base.model.AjaxResult
     * @description 修改用户信息
     * @author guohy
     * @date 2019/8/12-15:37
     */
    @PostMapping(value = "/save")
    @ResponseBody
    public AjaxResult save(Long[] ids, SysUser sysUser) {
        if (null == ids || ids.length == 0) {
            return error("角色不能为空");
        }
        sysUserService.save(sysUser, ids);
        return AjaxResult.success("success");
    }

    /**
     * @param userInfo
     * @return com.seasoft.base.model.AjaxResult
     * @description 获取用户信息
     * @author guohy
     * @date 2019/8/12-15:37
     */
    @RequestMapping(value = "/userInfoList")
    @ResponseBody
    public PageInfo<UserInfo> userInfoList(UserInfo userInfo) {
        userInfo.setDeptId(getUser().getDeptId());
        return sysUserService.selectUserInfoPage(userInfo);
    }


    /**
     * @description 修改个人信息
     * @author guohy
     * @date 2019/11/7-10:27
     * @param sysUser
     * @return com.tzstcl.base.model.AjaxResult
     */
    @PostMapping("/updateUserInfo")
    @ResponseBody
    public AjaxResult updateUserInfo(SysUser sysUser) {
        Long id = getUser().getId();
        if (null != id) {
            sysUser.setId(id);
            sysUser.setLoginName(null);
            Integer update = sysUserService.update(sysUser);
            if(update > 0){
                return success("修改成功");
            }
        }
        return error("修改失败");
    }

    /**
     * @description 修改密码
     * @author guohy
     * @date 2019/11/7-10:27
     * @param oldPassword
     * @param newPassword
     * @return com.tzstcl.base.model.AjaxResult
     */
    @PostMapping("/updatePassword")
    @ResponseBody
    public AjaxResult updatePassword(String oldPassword, String newPassword) {
        Long id = getUser().getId();
        AjaxResult ajaxResult = sysUserService.updatePassword(oldPassword, newPassword, id);
        return ajaxResult;
    }

    /**
     * 个人信息页面导航
     *
     * @return
     */
    @RequestMapping("/toPersonalInfo")
    public String toPersonalInfo(Model model) {
        String loginName = getUser().getLoginName();
        String name = getUser().getName();
        String mobile = getUser().getMobile();
        model.addAttribute("loginName", loginName);
        model.addAttribute("name", name);
        model.addAttribute("mobile", mobile);
        return "admin/personalInfo";
    }

    /**
     * @description 重置密码
     * @author guohy
     * @date 2019/11/1-16:47
     * @param sysUser
     * @return com.tzstcl.base.model.AjaxResult
     */
    @RequestMapping(value = "/resetPassword")
    @ResponseBody
    public AjaxResult resetPassword(SysUser sysUser) {
        sysUser.setSort(null);
        String password = new Sha256Hash(AppConstants.SYSTEM_PASSWARD).toHex();
        sysUser.setPassword(password);
        Integer reset = sysUserService.update(sysUser);
        if (reset == 0) {
            return error("修改失败");
        }
        return success("重置成功,重置后密码为：" + AppConstants.SYSTEM_PASSWARD);
    }

}
